package org.spring.springcloud.config.springSecurity.urlAccess;

import org.spring.springcloud.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;

/**
 * Created by liyu on 2018/5/14.
 * 功能：拦截请求url地址，获取所有能访问该地址的角色，存入Collection<ConfigAttribute>中
 */
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {


    @Autowired
    RoleService roleService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 获取当前的URL地址
        System.out.println("object的类型为:" + object.getClass());
        FilterInvocation filterInvocation = (FilterInvocation) object;
        String url = filterInvocation.getRequestUrl();
        System.out.println("访问的URL地址为(包括参数):" + url);
        url = filterInvocation.getRequest().getServletPath();
        System.out.println("访问的URL地址为:" + url);

        //根据当前的url地址，获取所有能访问该地址的角色，存入Collection<ConfigAttribute>中，
        // 源码中可以看到 SecurityConfig.createList(values)方法就是将一个字符串数组存到Collection<ConfigAttribute>中
//        List<Role> Roles = roleService.getAllRoleSByUrl(url);
//        int size = Roles.size();
//        String[] values = new String[size];
//        if(size > 0) {
//            for(int i=0; i<size ; i++) {
//                values[i] = Roles.get(i).getRoleName();
//                return SecurityConfig.createList(values);
//            }
//        }

        String[] values = new String[2];
        values[0]="ROLE_admin";
        values[1]="ROLE_test";

        return SecurityConfig.createList(values);

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
